<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function initWebSocket(wsUri) {
        var websocket = new WebSocket(wsUri);
        websocket.onopen = function (evt) {
          console.log("连接建立中... " + wsUri);
        };
        websocket.onclose = function (evt) {
          console.log("连接关闭中...", evt);
        };
        websocket.onmessage = function (evt) {
          console.log("收到来自服务端的消息：", evt.data);
        };
        websocket.onerror = function (evt) {
          console.log("发生错误...", evt);
        };
        return websocket;
      }
 
      var websocket = initWebSocket("ws://101.43.207.21:9502/");
      var msg,
        i = 0;
      var loop = setInterval(function () {
        msg = "Hello " + i++;
        if (websocket.readyState == WebSocket.OPEN) {
          websocket.send(msg);
          console.log("已发送消息：" + msg);
        } else {
          clearInterval(loop);
          console.log("连接已关闭，拜拜1~");
        }
      }, 3000);
    </script>
  </body>
</html>